import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus_tcp as modbus_tcp
import time


# ip是读取modbus的IP地址
# id是场地号
# flag代表状态，开灯、关灯、查询状态，分别用on,off,query来代表
def sendCont(ip, id, flag):
    # 连接MODBUS TCP从机
    master = modbus_tcp.TcpMaster(host=ip)
    master.set_timeout(5.0)
    # 获取状态
    id_flag = int(getflag(flag))
    id_num = id - 1
    if id == 10000:
        if id_flag == 1:
            for i in range(0, 21):
                master.execute(1, cst.WRITE_SINGLE_REGISTER, i, output_value=1)
                time.sleep(1.5)
            return ("success", "allon")
        elif id_flag == 0:
            for i in range(0, 21):
                master.execute(1, cst.WRITE_SINGLE_REGISTER, i, output_value=0)
                time.sleep(1.5)
            return ("success", "alloff")
        elif id_flag == 11:
            all_res = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 21)
            return alllist(all_res)
        else:
            return ("fail", "error")
    if id_flag == 11:
        # 读寄存器
        c_input = master.execute(1, cst.READ_HOLDING_REGISTERS, id_num, 1)
        return getchaxun(c_input)
    else:
        # 单个读写寄存器操作
        master.execute(1, cst.WRITE_SINGLE_REGISTER, id_num, output_value=id_flag)
        # 读寄存器
        res_chaxun = master.execute(1, cst.READ_HOLDING_REGISTERS, id_num, 1)
        return getchaxun(res_chaxun)


def alllist(res):
    getlist = list(res)
    for item in range(len(getlist)):
        if getlist[item] == 1:
            getlist[item] = 'on'
        elif getlist[item] == 0:
            getlist[item] = 'off'
        else:
            getlist[item] = 'error'
    return getlist


def getchaxun(id):
    if id[0] == 1:
        return ("success", "on")
    elif id[0] == 0:
        return ("success", "off")
    else:
        return ("fail", "error")


def getflag(flag):
    if flag == 'on':
        return '1'
    elif flag == 'off':
        return '0'
    elif flag == 'query':
        return '11'
    else:
        return 'error'


if __name__ == "__main__":
    try:
        res = sendCont('10.32.250.250', 10000, 'query')
        print(res)

    except modbus_tk.modbus.ModbusError as e:
        print("%s- Code=%d" % (e, e.get_exception_code()))
